package pos.control;

import java.util.ListIterator;
import pos.entity.PriceAdjustment;
import pos.entity.PriceAdjustment.PriceAdjustmentType;
import pos.entity.PurchasedItem;
import pos.entity.Tax;

/**
 *
 * @author Justin Hume
 */
public class TaxControl {

    //Private fields
    private Tax _currentTaxRates;

    //Constructor
    public TaxControl() {

        //Get current tax rates
        _currentTaxRates = new Tax();
    }

    //Public Interface

    //Adds tax priceAdjustments for a purchased items
    public PurchasedItem addPurchasedItemTax(PurchasedItem purchasedItem) {

        //Ensure tax has not already been added; if tax has been added remove
        //those price adjustments
        purchasedItem = removeTaxes(purchasedItem);

        //Create a price adjustment for each relevant tax:

        //HST
        double valueOfHST = purchasedItem.getTotalPrice()*_currentTaxRates.getHST();

        PriceAdjustment HSTAdjustment = new PriceAdjustment(
                pos.util.IDGenerator.getID(),
                valueOfHST,
                1,
                PriceAdjustmentType._TAX_,
                "HST",
                purchasedItem.getPurchaseItemId(),
                -1);

        //Environmental tax
        double valueOfEnviroTax = purchasedItem.getTotalPrice()*_currentTaxRates.getEnvironmentalTax();

        PriceAdjustment EnviroAdjustment = new PriceAdjustment(
                pos.util.IDGenerator.getID(),
                valueOfEnviroTax,
                1,
                PriceAdjustmentType._TAX_,
                "Environmental disposal tax",
                purchasedItem.getPurchaseItemId(),
                -1);

        //Add price adjustments to the purchased item
        purchasedItem.setPriceAdjustments(HSTAdjustment);
        purchasedItem.setPriceAdjustments(EnviroAdjustment);

        return purchasedItem;
    }

    //Checks if a particular tax has already been added to the purchased item
    private PurchasedItem removeTaxes(PurchasedItem purchasedItem) {

        //If a price adjustment type of _TAX_ is found remove it
        ListIterator adjIterator = purchasedItem.getPriceAdjustments().listIterator();

        while(adjIterator.hasNext()) {

            PriceAdjustment adj = (PriceAdjustment)adjIterator.next();

            if (adj.getPriceAdjustmentType() == PriceAdjustmentType._TAX_) {

                adjIterator.remove();
            }   
        }
        
        return purchasedItem;
    }
}
